<template>
  <div class="container">
    <el-dialog
      :title="dialogTitle"
      :visible="dialogVisible"
      :close-on-click-modal="false"
      @close="closeDialogFn"
      @open="opensimpleApi"
      width="400px"
    >
      <el-form ref="ruleForm" :model="formData" :rules="rules">
        <el-form-item label="所属学科" prop="subjectID" label-width="80px">
          <el-select
            style="width: 280px"
            v-model="formData.subjectID"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in tagsList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" prop="tagName" label-width="80px">
          <el-input v-model="formData.tagName" placeholder="请选择标签名称"></el-input>
        </el-form-item>
      </el-form>
      <!-- footer插槽 -->
      <template v-slot:footer>
        <el-button @click="closeDialogFn">取消</el-button>
        <el-button type="primary" @click="confirmAddSubject">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects'
import { add, update } from '@/api/hmmm/tags'
export default {
  name: 'tags-add',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    dialogTitle: {
      type: String,
      default: '新增标签'
    },
    formData: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      tagsList: [],
      rules: {
        tagName: [{ required: true, message: '请输入标签名称', trigger: 'blur' }],
        subjectID: [{ required: true, message: '请输入标签名称', trigger: 'change' }]
      }
    }
  },
  methods: {
    /** 关闭dialog */
    closeDialogFn () {
      this.$emit('update:dialogVisible', false)
      this.$refs.ruleForm.resetFields()
      this.$emit('update:formData', {})
    },
    /** 点击确定提交请求 */
    confirmAddSubject () {
      this.$refs.ruleForm.validate(async flag => {
        if (!flag) return
        if (this.formData.id) {
          await update(this.formData)
          this.$message.success('修改标签成功')
        } else {
          await add(this.formData)
          this.$message.success('新增标签成功')
        }
        this.closeDialogFn()
        this.$parent.tagsListApi()
      })
    },
    /** 获取学科简单列表 */
    async simpleApi (subjectName) {
      const { data: res } = await simple({ subjectName })
      this.tagsList = res
    },
    opensimpleApi () {
      this.simpleApi(this.formData.subjectName)
    }
  }
}
</script>

<style lang="scss" scoped></style>
